import pygame
import random
import os
import math

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 背景切换相关设置
BACKGROUND_INTERVAL = 2000  # 切换间隔2秒（毫秒）
current_background = 0
background_images = []
background_timer = pygame.time.get_ticks()

# 胜利/失败背景设置
WIN_BG_PATH = "image/win_bg.jpeg"  # 胜利背景图片路径
LOSE_BG_PATH = "image/lose_bg.jpeg"  # 失败背景图片路径
win_background = None
lose_background = None

# 新增：消除按钮图片设置
CLEAR_BUTTON_IMG_PATH = "image/clear_button.png"  # 消除按钮图片路径
clear_button_img = None  # 按钮图片对象

# 新增：按钮悬停效果设置
BUTTON_HOVER_COLOR = (220, 220, 220)  # 按钮悬停时的颜色
button_hover = False  # 按钮是否被悬停

# 颜色定义
BG_COLOR = (255, 255, 255)
BUTTON_COLOR = (200, 200, 200)  # 清除按钮默认颜色（无图片时使用）
TEXT_COLOR = (0, 0, 0)  # 按钮文字颜色
RESTART_BUTTON_COLOR = (255, 100, 100)  # 重新开始按钮颜色
WIN_BUTTON_COLOR = (0, 200, 0)  # 胜利按钮颜色

# 粒子效果颜色
PARTICLE_COLORS = [
    (255, 100, 100),  # 红色系
    (100, 255, 100),  # 绿色系
    (100, 100, 255),  # 蓝色系
    (255, 255, 100),  # 黄色系
    (255, 100, 255),  # 紫色系
]

# 卡片尺寸和间距
CARD_WIDTH = 55
CARD_HEIGHT = 70
SPACING = 5  # 调整后的卡片间距
GROUP_SPACING = 20  # 每组卡片中间的间隔，调整为与原游戏接近的值

# 游戏区域布局
GRID_ROWS = 5  # 调整为与原游戏一致的行数
GRID_COLS = 4  # 调整为与原游戏一致的列数
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) + (GRID_COLS - 1) * GROUP_SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 150  # 调整游戏区域的顶部位置

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 清除按钮设置
BUTTON_WIDTH = 80
BUTTON_HEIGHT = 40
BUTTON_LEFT = SCREEN_WIDTH - BUTTON_WIDTH - 20
BUTTON_TOP = 60  # 按钮位置

# 撤销按钮设置
UNDO_BUTTON_WIDTH = 80
UNDO_BUTTON_HEIGHT = 80
UNDO_BUTTON_LEFT = BUTTON_LEFT - UNDO_BUTTON_WIDTH - 10
UNDO_BUTTON_TOP = BUTTON_TOP

# 洗牌按钮设置
SHUFFLE_BUTTON_WIDTH = 80
SHUFFLE_BUTTON_HEIGHT = 80
SHUFFLE_BUTTON_LEFT = UNDO_BUTTON_LEFT - SHUFFLE_BUTTON_WIDTH - 10
SHUFFLE_BUTTON_TOP = BUTTON_TOP

# 重新开始按钮设置
RESTART_BUTTON_WIDTH = 160
RESTART_BUTTON_HEIGHT = 60
RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_WIDTH) // 2
RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50

# 胜利按钮设置
WIN_BUTTON_WIDTH = 200
WIN_BUTTON_HEIGHT = 60
WIN_BUTTON_LEFT = (SCREEN_WIDTH - WIN_BUTTON_WIDTH) // 2
WIN_BUTTON_TOP = SCREEN_HEIGHT // 2 + 120

# 加载图片
try:
    image_folder = os.path.join(os.path.dirname(__file__), "image")

    # 加载消除按钮图片
    if os.path.exists(CLEAR_BUTTON_IMG_PATH):
        clear_button_img = pygame.image.load(CLEAR_BUTTON_IMG_PATH)
        clear_button_img = pygame.transform.scale(clear_button_img, (BUTTON_WIDTH, BUTTON_HEIGHT))
        print("消除按钮图片加载成功")
    else:
        print("消除按钮图片不存在，使用默认颜色")

    # 加载4张背景图片
    for i in range(4):
        bg_path = os.path.join(image_folder, f"bg{i + 1}.jpeg")
        if os.path.exists(bg_path):
            img = pygame.image.load(bg_path)
            img = pygame.transform.scale(img, (SCREEN_WIDTH, SCREEN_HEIGHT))
            background_images.append(img)
            print(f"背景图片 {i + 1} 加载成功")
        else:
            print(f"背景图片 {bg_path} 不存在，使用默认背景")
            # 创建纯色背景作为替代
            solid_color = [(240, 240, 240), (220, 230, 240), (230, 245, 230), (245, 235, 220)][i % 4]
            solid_bg = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            solid_bg.fill(solid_color)
            background_images.append(solid_bg)

    if not background_images:
        raise Exception("没有找到任何背景图片")

    # 加载胜利/失败背景
    if os.path.exists(WIN_BG_PATH):
        win_background = pygame.image.load(WIN_BG_PATH)
        win_background = pygame.transform.scale(win_background, (SCREEN_WIDTH, SCREEN_HEIGHT))
        print("胜利背景加载成功")
    else:
        print("胜利背景图片不存在，使用默认样式")
        win_background = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
        win_background.fill((0, 255, 0, 128))  # 绿色半透明背景

    if os.path.exists(LOSE_BG_PATH):
        lose_background = pygame.image.load(LOSE_BG_PATH)
        lose_background = pygame.transform.scale(lose_background, (SCREEN_WIDTH, SCREEN_HEIGHT))
        print("失败背景加载成功")
    else:
        print("失败背景图片不存在，使用默认样式")
        lose_background = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
        lose_background.fill((255, 0, 0, 128))  # 红色半透明背景

    # 初始背景
    background_img = background_images[current_background]
    print("主背景图像加载成功")

    # 加载卡片图片
    card_images = []
    for i in range(5):
        if i == 0:
            tile_path = os.path.join(image_folder, "tile.png")
        else:
            tile_path = os.path.join(image_folder, f"tile{i}.png")

        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.dirname(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

    # 加载撤销按钮图片
    undo_button_img = pygame.image.load(os.path.join(image_folder, "undo_button.png"))
    undo_button_img = pygame.transform.scale(undo_button_img, (UNDO_BUTTON_WIDTH, UNDO_BUTTON_HEIGHT))
    print("撤销按钮图片加载成功")

    # 加载洗牌按钮图片
    shuffle_button_img = pygame.image.load(os.path.join(image_folder, "shuffle_button.png"))
    shuffle_button_img = pygame.transform.scale(shuffle_button_img, (SHUFFLE_BUTTON_WIDTH, SHUFFLE_BUTTON_HEIGHT))
    print("洗牌按钮图片加载成功")

    # 加载重新开始按钮图片（如果存在）
    restart_button_img_path = os.path.join(image_folder, "restart_button.png")
    if os.path.exists(restart_button_img_path):
        restart_button_img = pygame.image.load(restart_button_img_path)
        restart_button_img = pygame.transform.scale(restart_button_img, (RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT))
        print("重新开始按钮图片加载成功")
    else:
        restart_button_img = None
        print("重新开始按钮图片不存在，将使用默认样式")

except Exception as e:
    print(f"图片加载失败: {e}")
    card_images = []  # 初始化card_images为空列表
    COLORS = [
        (255, 0, 0),
        (255, 255, 0),
        (0, 255, 0),
        (0, 0, 255),
        (128, 0, 128)
    ]
    background_images = []
    # 创建一个默认背景
    default_bg = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
    default_bg.fill(BG_COLOR)
    background_images.append(default_bg)
    background_img = default_bg
    slot_bg_img = None
    undo_button_img = None
    shuffle_button_img = None
    restart_button_img = None
    win_background = default_bg
    lose_background = default_bg
    clear_button_img = None  # 确保清除按钮图片也被初始化为None


# 粒子类
class Particle:
    def __init__(self, x, y, color, size=3):
        self.x = x
        self.y = y
        self.color = color
        self.size = size
        self.alpha = 255
        # 随机速度
        angle = random.uniform(0, 2 * math.pi)
        speed = random.uniform(1, 4)
        self.vx = speed * math.cos(angle)
        self.vy = speed * math.sin(angle)
        # 随机加速度
        self.gravity = random.uniform(0.05, 0.15)
        self.friction = random.uniform(0.95, 0.99)  # 添加摩擦力

    def update(self):
        self.vx *= self.friction
        self.vy *= self.friction
        self.vy += self.gravity
        self.x += self.vx
        self.y += self.vy
        self.alpha -= 5
        return self.alpha <= 0

    def draw(self, surface):
        s = pygame.Surface((self.size * 2, self.size * 2), pygame.SRCALPHA)
        pygame.draw.circle(s, (*self.color, self.alpha), (self.size, self.size), self.size)
        surface.blit(s, (int(self.x - self.size), int(self.y - self.size)))


# 三连消除特效粒子类
class ComboParticle(Particle):
    def __init__(self, x, y, color, size=5):
        super().__init__(x, y, color, size)
        angle = random.uniform(0, 2 * math.pi)
        speed = random.uniform(3, 6)
        self.vx = speed * math.cos(angle)
        self.vy = speed * math.sin(angle)
        self.gravity = random.uniform(0.01, 0.05)
        self.friction = random.uniform(0.97, 0.99)
        self.rotation = random.uniform(0, 360)
        self.rotation_speed = random.uniform(-5, 5)

    def update(self):
        self.vx *= self.friction
        self.vy *= self.friction
        self.vy += self.gravity
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.rotation_speed
        self.alpha -= 5
        return self.alpha <= 0

    def draw(self, surface):
        s = pygame.Surface((self.size * 4, self.size * 4), pygame.SRCALPHA)
        pygame.draw.circle(s, (*self.color, self.alpha), (self.size * 2, self.size * 2), self.size)
        rotated_surface = pygame.transform.rotate(s, self.rotation)
        rotated_rect = rotated_surface.get_rect(center=(int(self.x), int(self.y)))
        surface.blit(rotated_surface, rotated_rect)


# 初始化游戏
def init_game():
    global slots, score, game_over, game_won, button_uses, undo_button_uses, shuffle_button_uses, grid
    slots = []
    score = 0
    game_over = False
    game_won = False
    button_uses = 3
    undo_button_uses = 3
    shuffle_button_uses = 3

    # 初始化卡片堆
    grid = []
    for row in range(GRID_ROWS):
        grid_row = []
        for col in range(GRID_COLS):
            layers = random.randint(3, 5)
            max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
            stack = [random.randint(0, max_card_type) for _ in range(layers)]
            stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
            grid_row.append(stack)
        grid.append(grid_row)


# 检查是否胜利
def check_victory():
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0


# 创建普通粒子效果
def create_particles(x, y, card_type, count=30):
    if card_images:
        # 使用卡片颜色创建粒子
        color = PARTICLE_COLORS[card_type % len(PARTICLE_COLORS)]
    else:
        # 使用预设颜色创建粒子
        color = COLORS[card_type % len(COLORS)]

    for _ in range(count):
        size = random.randint(2, 5)
        particle = Particle(x, y, color, size)
        particles.append(particle)


# 创建三连消除粒子效果
def create_combo_particles(x, y, card_type):
    if card_images:
        color = PARTICLE_COLORS[card_type % len(PARTICLE_COLORS)]
    else:
        color = COLORS[card_type % len(COLORS)]

    # 创建主爆炸效果
    for _ in range(100):
        size = random.randint(3, 7)
        particle = ComboParticle(x, y, color, size)
        particles.append(particle)

    # 添加"三连消"文本效果
    combo_text.append({
        'text': "三连消!",
        'x': x,
        'y': y - 50,
        'alpha': 255,
        'size': 36,
        'color': (255, 215, 0)  # 金色
    })


# 洗牌函数
def shuffle_grid():
    for row in grid:
        for stack in row:
            random.shuffle(stack)
    random.shuffle(grid)


# 初始化游戏
init_game()

# 游戏状态
moving_card = None  # 正在移动的卡片
start_pos = (0, 0)  # 起始位置
end_pos = (0, 0)  # 目标位置
step = 5  # 每次移动的步数
particles = []  # 粒子效果列表
combo_text = []  # 显示"三连消"文本

# 主循环
clock = pygame.time.Clock()
running = True

while running:
    current_time = pygame.time.get_ticks()

    # 背景切换逻辑（游戏进行中）
    if not game_over and len(background_images) > 1:
        if current_time - background_timer > BACKGROUND_INTERVAL:
            current_background = (current_background + 1) % len(background_images)
            background_img = background_images[current_background]
            background_timer = current_time

    # 检测鼠标位置，判断是否悬停在清除按钮上
    mouse_x, mouse_y = pygame.mouse.get_pos()
    button_hover = (BUTTON_LEFT <= mouse_x < BUTTON_LEFT + BUTTON_WIDTH and
                    BUTTON_TOP <= mouse_y < BUTTON_TOP + BUTTON_HEIGHT)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()

            # 游戏胜利时的按钮处理
            if game_won and game_over:
                # 恭喜胜利按钮点击检测
                if (WIN_BUTTON_LEFT <= mouse_x < WIN_BUTTON_LEFT + WIN_BUTTON_WIDTH and
                        WIN_BUTTON_TOP <= mouse_y < WIN_BUTTON_TOP + WIN_BUTTON_HEIGHT):
                    init_game()  # 重新开始游戏
                    continue

            # 游戏结束时检查是否点击重新开始按钮（失败状态）
            if not game_won and game_over and (
                    RESTART_BUTTON_LEFT <= mouse_x < RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH and
                    RESTART_BUTTON_TOP <= mouse_y < RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT
            ):
                init_game()  # 重新初始化游戏
                continue  # 跳过剩余的事件处理

            # 游戏未结束时处理正常游戏逻辑
            if not game_over:
                clicked_row = None
                clicked_col = None

                # 检查是否点击了清除按钮
                if button_hover and button_uses > 0:
                    slots = []
                    button_uses -= 1

                # 检查是否点击了撤销按钮
                if UNDO_BUTTON_LEFT <= mouse_x < UNDO_BUTTON_LEFT + UNDO_BUTTON_WIDTH and \
                        UNDO_BUTTON_TOP <= mouse_y < UNDO_BUTTON_TOP + UNDO_BUTTON_HEIGHT and \
                        undo_button_uses > 0:
                    if slots:
                        slots.pop()
                        undo_button_uses -= 1

                # 检查是否点击了洗牌按钮
                if SHUFFLE_BUTTON_LEFT <= mouse_x < SHUFFLE_BUTTON_LEFT + SHUFFLE_BUTTON_WIDTH and \
                        SHUFFLE_BUTTON_TOP <= mouse_y < SHUFFLE_BUTTON_TOP + SHUFFLE_BUTTON_HEIGHT and \
                        shuffle_button_uses > 0:
                    shuffle_grid()
                    shuffle_button_uses -= 1

                else:
                    # 遍历卡片堆寻找被点击的顶层卡片
                    for row in range(GRID_ROWS):
                        for col in range(GRID_COLS):
                            stack = grid[row][col]
                            if not stack:
                                continue
                            # 计算顶层卡片实际位置
                            base_x = GRID_LEFT + col * (CARD_WIDTH + SPACING + GROUP_SPACING)
                            base_y = GRID_TOP + row * (CARD_HEIGHT + SPACING)

                            # 碰撞检测
                            if (base_x <= mouse_x < base_x + CARD_WIDTH and
                                    base_y <= mouse_y < base_y + CARD_HEIGHT):
                                clicked_row, clicked_col = row, col
                                break
                        if clicked_row is not None:
                            break

                    if clicked_row is not None and clicked_col is not None:
                        if len(grid[clicked_row][clicked_col]) > 0:
                            if len(slots) >= SLOT_COLS:
                                game_over = True
                                continue

                            moving_card = grid[clicked_row][clicked_col].pop()
                            start_pos = (base_x, base_y)
                            # 计算槽位中的目标位置
                            end_pos = (SLOT_LEFT + len(slots) * (CARD_WIDTH + 5), SLOT_TOP)

    # 移动卡片
    if moving_card is not None:
        x, y = start_pos
        target_x, target_y = end_pos
        if abs(x - target_x) > step:
            x += step if x < target_x else -step
        else:
            x = target_x
        if abs(y - target_y) > step:
            y += step if y < target_y else -step
        else:
            y = target_y
        start_pos = (x, y)
        if x == target_x and y == target_y:
            slots.append(moving_card)
            moving_card = None

            # 检查是否有三个相同的卡片，若有则消除
            if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                # 获取消除卡片的位置和类型
                card_type = slots[-1]
                combo_center_x = SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5) + CARD_WIDTH // 2
                combo_center_y = SLOT_TOP + CARD_HEIGHT // 2

                # 创建三连消除特效
                create_combo_particles(combo_center_x, combo_center_y, card_type)

                # 为每个被消除的卡片创建普通粒子效果
                for i in range(3):
                    card_x = SLOT_LEFT + (len(slots) - 3 + i) * (CARD_WIDTH + 5)
                    card_y = SLOT_TOP
                    create_particles(card_x + CARD_WIDTH // 2, card_y + CARD_HEIGHT // 2, card_type, 20)

                del slots[-3:]
                score += 1

            if len(slots) >= SLOT_COLS:
                game_over = True

            if check_victory():
                game_won = True
                game_over = True

    # 更新粒子
    particles = [p for p in particles if not p.update()]

    # 更新三连消文本
    for text_info in combo_text[:]:
        text_info['y'] -= 1  # 向上移动
        text_info['alpha'] -= 5  # 淡出
        if text_info['alpha'] <= 0:
            combo_text.remove(text_info)

    # 绘制界面
    if game_over:
        # 绘制胜利/失败背景
        if game_won and win_background:
            screen.blit(win_background, (0, 0))
        elif not game_won and lose_background:
            screen.blit(lose_background, (0, 0))
        else:
            screen.fill(BG_COLOR)

        # 绘制半透明遮罩
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))
        screen.blit(overlay, (0, 0))

        # 绘制游戏结束文本
        font = pygame.font.Font(None, 48)
        text = font.render("恭喜胜利！" if game_won else "游戏结束",
                           True, (0, 255, 0) if game_won else (255, 0, 0))
        text_rect = text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 60))
        screen.blit(text, text_rect)

        # 绘制最终得分
        score_text = font.render(f"得分: {score}", True, (255, 255, 255))
        score_rect = score_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
        screen.blit(score_text, score_rect)

        # 确保字体对象已定义
        button_font = pygame.font.Font(None, 32)  # 修复：添加字体定义

        # 绘制胜利按钮（只在胜利时显示）
        if game_won:
            pygame.draw.rect(screen, WIN_BUTTON_COLOR,
                             (WIN_BUTTON_LEFT, WIN_BUTTON_TOP, WIN_BUTTON_WIDTH, WIN_BUTTON_HEIGHT), border_radius=15)
            button_text = button_font.render("再来一局", True, (255, 255, 255))
            button_rect = button_text.get_rect(
                center=(WIN_BUTTON_LEFT + WIN_BUTTON_WIDTH // 2, WIN_BUTTON_TOP + WIN_BUTTON_HEIGHT // 2))
            screen.blit(button_text, button_rect)

        # 绘制重新开始按钮（只在失败时显示）
        if not game_won:
            if restart_button_img:
                screen.blit(restart_button_img, (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP))
            else:
                pygame.draw.rect(screen, RESTART_BUTTON_COLOR,
                                 (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP, RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT),
                                 border_radius=15)
            restart_text = button_font.render("重新开始", True, (255, 255, 255))
            restart_rect = restart_text.get_rect(center=(
            RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH // 2, RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT // 2))
            screen.blit(restart_text, restart_rect)

    else:
        # 游戏进行中显示普通背景
        if background_img:
            screen.blit(background_img, (0, 0))
        else:
            screen.fill(BG_COLOR)

        # 绘制卡片堆（叠罗汉效果）
        for row in range(GRID_ROWS):
            for col in range(GRID_COLS):
                stack = grid[row][col]
                if not stack:
                    continue
                base_x = GRID_LEFT + col * (CARD_WIDTH + SPACING + GROUP_SPACING)
                base_y = GRID_TOP + row * (CARD_HEIGHT + SPACING)

                # 绘制所有层卡片
                for index, card_type in enumerate(stack):
                    offset_y = index * 3  # 每张卡片之间的纵向偏移量
                    if card_images:
                        screen.blit(card_images[card_type], (base_x, base_y + offset_y))
                    else:
                        pygame.draw.rect(screen, COLORS[card_type],
                                         (base_x, base_y + offset_y, CARD_WIDTH, CARD_HEIGHT))

        # 绘制槽位中的卡片
        for i, card in enumerate(slots):
            x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            if card_images:
                screen.blit(card_images[card], (x, SLOT_TOP))
            else:
                pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))

        # 绘制清除按钮（新增图片支持）
        if clear_button_img:
            screen.blit(clear_button_img, (BUTTON_LEFT, BUTTON_TOP))
        else:
            # 若无图片，则使用默认颜色绘制按钮，并添加悬停效果
            button_color = BUTTON_HOVER_COLOR if button_hover else BUTTON_COLOR
            pygame.draw.rect(screen, button_color, (BUTTON_LEFT, BUTTON_TOP, BUTTON_WIDTH, BUTTON_HEIGHT),
                             border_radius=10)

        # 绘制清除按钮文字
        font = pygame.font.Font(None, 24)
        text = font.render(f"清除 ({button_uses})", True, TEXT_COLOR)
        text_rect = text.get_rect(center=(BUTTON_LEFT + BUTTON_WIDTH // 2, BUTTON_TOP + BUTTON_HEIGHT // 2))
        screen.blit(text, text_rect)

        # 绘制撤销按钮
        if undo_button_img:
            screen.blit(undo_button_img, (UNDO_BUTTON_LEFT, UNDO_BUTTON_TOP))
        else:
            pygame.draw.rect(screen, BUTTON_COLOR,
                             (UNDO_BUTTON_LEFT, UNDO_BUTTON_TOP, UNDO_BUTTON_WIDTH, UNDO_BUTTON_HEIGHT),
                             border_radius=10)
        text = font.render(f"撤销 ({undo_button_uses})", True, TEXT_COLOR)
        text_rect = text.get_rect(
            center=(UNDO_BUTTON_LEFT + UNDO_BUTTON_WIDTH // 2, UNDO_BUTTON_TOP + UNDO_BUTTON_HEIGHT // 2))
        screen.blit(text, text_rect)

        # 绘制洗牌按钮
        if shuffle_button_img:
            screen.blit(shuffle_button_img, (SHUFFLE_BUTTON_LEFT, SHUFFLE_BUTTON_TOP))
        else:
            pygame.draw.rect(screen, BUTTON_COLOR,
                             (SHUFFLE_BUTTON_LEFT, SHUFFLE_BUTTON_TOP, SHUFFLE_BUTTON_WIDTH, SHUFFLE_BUTTON_HEIGHT),
                             border_radius=10)
        text = font.render(f"洗牌 ({shuffle_button_uses})", True, TEXT_COLOR)
        text_rect = text.get_rect(
            center=(SHUFFLE_BUTTON_LEFT + SHUFFLE_BUTTON_WIDTH // 2, SHUFFLE_BUTTON_TOP + SHUFFLE_BUTTON_HEIGHT // 2))
        screen.blit(text, text_rect)

        # 绘制状态信息
        font = pygame.font.Font(None, 36)
        text = font.render(f"得分: {score}", True, (0, 0, 0))
        screen.blit(text, (20, 20))

        # 绘制背景切换指示器
        indicator_font = pygame.font.Font(None, 20)
        indicator_text = indicator_font.render(f"背景: {current_background + 1}/{len(background_images)}", True,
                                               (0, 0, 0))
        screen.blit(indicator_text, (20, 60))

        # 绘制槽位容量提示
        capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
        screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))

        # 绘制正在移动的卡片
        if moving_card is not None:
            if card_images:
                screen.blit(card_images[moving_card], start_pos)
            else:
                pygame.draw.rect(screen, COLORS[moving_card], (start_pos[0], start_pos[1], CARD_WIDTH, CARD_HEIGHT))

    # 绘制粒子效果
    for particle in particles:
        particle.draw(screen)

    # 绘制三连消文本
    for text_info in combo_text:
        font = pygame.font.Font(None, text_info['size'])
        text_surface = font.render(text_info['text'], True, text_info['color'])
        text_surface.set_alpha(text_info['alpha'])
        text_rect = text_surface.get_rect(center=(text_info['x'], text_info['y']))
        screen.blit(text_surface, text_rect)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()